package cn.zeal4j;

import cn.zeal4j.relationmapping.domain.Customer;
import cn.zeal4j.relationmapping.domain.Order;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @file Hibernate
 * @create 2020 09 24 11:23
 */
public class HibernateTest2 {

    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;

    @Before
    public void initResource() {
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate/hibernate.cfg.xml").build();
        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
    }

    @Test
    public void manyToOneRelationMappingTest() {
        Customer customer = new Customer();
        customer.setName("客户01");

        Order order01 = new Order();
        order01.setName("订单01");

        Order order02 = new Order();
        order02.setName("订单02");

        order01.setCustomer(customer);
        order02.setCustomer(customer);

        session.save(customer);
        session.save(order01);
        session.save(order02);

        final int exactParam = 100;

        final String HQL_SENTENCE = "FROM xxx.xxx.DomainClass AS dc WHERE dc.someProperty = ? ";

        Query query = session.createQuery(HQL_SENTENCE);

        query.setParameter(0, exactParam);

        final List<Object> HQL_PARAM_LIST = new ArrayList<>();
        // 添加指定位置的参数值
        HQL_PARAM_LIST.add("param1");
        HQL_PARAM_LIST.add("param2");
        HQL_PARAM_LIST.add("param3");
        // ...

        // 确定之后转换数组
        Object[] array = HQL_PARAM_LIST.toArray();

        for (int i = 0; i < array.length; i++) {
            query.setParameter(i, array[i]);
        }


    }

    @Test
    public void hibernateOperateAPI() {

    }

    @Test
    public void manyToOneRelationMappingQueryTest() {
        Order order = session.get(Order.class, 1);
        System.out.println(order.getName());

        Customer customer = order.getCustomer();
        System.out.println(customer.getName());


    }




    @After
    public void releaseResource() {
        transaction.commit();
        session.close();
        sessionFactory.close();
    }

}
